﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataImporter.Models;
using System.Text.RegularExpressions;

namespace DataImporter.Modules
{
    public partial class ucXXGZFY : UserControl
    {
        #region Fields

        /// <summary>
        /// 数据列表
        /// </summary>
        private List<NCDP_XXGZFY> nCDP_XXGZFies = new List<NCDP_XXGZFY>();
        /// <summary>
        /// 推荐项目
        /// </summary>
        private List<NCDP_XXGZFYTJXM> nCDP_XXGZFYTJXMs = new List<NCDP_XXGZFYTJXM>();

        #endregion

        public ucXXGZFY()
        {
            InitializeComponent();
            this.cbbType.SelectedIndex = 0;
        }

        #region Methods

        /// <summary>
        /// 点击分析按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAnalyze_Click(object sender, EventArgs e)
        {
            if (this.rtbContent.Text.IsNullOrEmpty())
            {
                MessageBox.Show("要解析的内容不能为空");
                return;
            }
            var lines = this.rtbContent.Lines;
            switch (this.cbbType.Text)
            {
                case "年龄":
                    AnalyzeAge(this.rtbContent.Lines);
                    break;
                case "个人病史":
                    AnalyzeGRBS(lines);
                    break;
                case "生活习惯":
                    AnalyzeSHXG(lines);
                    break;
                case "所在地区":
                    AnalyzeSZDQ(lines);
                    break;
                case "疫情期间可能感染":
                    AnalyzeKNGR(lines);
                    break;
                case "疫情期间疑似症状":
                    AnalyzeYSZZ(lines);
                    break;
                case "推荐项目":
                    AnalyzeTJXM(lines);
                    return;
            }
            foreach (var line in nCDP_XXGZFies)
            {
                var items = line.NPXX_Recommend?.Split("\t；".ToArray(), StringSplitOptions.RemoveEmptyEntries) ?? new string[0];
                var ids = "";
                foreach (var item in items)
                {
                    var tjxm = nCDP_XXGZFYTJXMs.Find(c => c.NPTJ_Content == HandleRecommanded(item));
                    if (null == tjxm)
                    {
                        MessageBox.Show($"{item}找不到ID");
                        return;
                    }
                    ids += $"{tjxm.NPTJ_ID},";
                }
                ids = ids.TrimEnd(',');
                line.NPXX_Recommend = ids;
            }

            this.dgvData.DataSource = null;
            this.dgvData.DataSource = nCDP_XXGZFies;
        }

        /// <summary>
        /// 处理推荐
        /// </summary>
        /// <param name="recommanded">要处理的推荐内容</param>
        /// <returns>结果</returns>
        private string HandleRecommanded(string recommanded)
        {
            return Regex.Replace(Regex.Replace(recommanded.Trim().Trim('\t', '。').TrimStart('£', '*', '¨'), "[¨£*]", "，"), "（\\d+）", "");
        }

        /// <summary>
        /// 解析年龄
        /// </summary>
        /// <param name="lines">要解析的内容</param>
        private void AnalyzeAge(string[] lines)
        {
            nCDP_XXGZFies.Clear();
            nCDP_XXGZFies.Add(new NCDP_XXGZFY
            {
                NPXX_Name = "年龄",
                NPXX_IsRequired = true,
                NPXX_Type = 3,
                NPXX_Code = 0,
                NPXX_Order = 5
            });
            var order = 5;
            try
            {
                foreach (var line in lines)
                {
                    if (line.IsNullOrEmpty())
                        continue;
                    var items = line.Split('\t');
                    nCDP_XXGZFies.Add(new NCDP_XXGZFY
                    {
                        NPXX_Name = items[0].Replace("&", "&&"),
                        NPXX_Score = int.Parse(items[2]),
                        NPXX_Order = order,
                        NPXX_Code = 0,
                        NPXX_Recommend = items[4]
                    });
                    order += 5;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 解析个人病史
        /// </summary>
        /// <param name="lines">要解析的内容</param>
        private void AnalyzeGRBS(string[] lines)
        {
            nCDP_XXGZFies.Clear();
            nCDP_XXGZFies.Add(new NCDP_XXGZFY
            {
                NPXX_Name = "个人病史",
                NPXX_Type = 2,
                NPXX_Order = 10,
                NPXX_Code = 1,
                NPXX_IsRequired = false
            });
            var category = string.Empty;
            var order = 5;
            try
            {
                foreach (var line in lines)
                {
                    if (line.IsNullOrEmpty())
                        continue;
                    var items = line.Split('\t');
                    if (items[2].IsNullOrEmpty())
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Type = 4,
                            NPXX_Name = items[0],
                            NPXX_Code = 1,
                            NPXX_Order = order,
                        });
                    else
                    {
                        if (!items[1].IsNullOrEmpty())
                            category = items[1].Trim();
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Name = items[2].Trim(),
                            NPXX_Category = category,
                            NPXX_Score = int.Parse(items[3]),
                            NPXX_Code = 1,
                            NPXX_Recommend = items[5],
                            NPXX_Order = order,
                        });
                    }
                    order += 5;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 解析生活习惯
        /// </summary>
        /// <param name="lines">要解析的内容</param>
        private void AnalyzeSHXG(string[] lines)
        {
            nCDP_XXGZFies.Clear();
            nCDP_XXGZFies.Add(new NCDP_XXGZFY
            {
                NPXX_Name = "生活习惯",
                NPXX_Type = 2,
                NPXX_Order = 15,
                NPXX_Code = 2,
                NPXX_IsRequired = false
            });
            var order = 5;
            try
            {
                foreach (var line in lines)
                {
                    if (line.IsNullOrEmpty())
                        continue;
                    var items = line.Split('\t');
                    if (items[2].IsNullOrEmpty())
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Type = 4,
                            NPXX_Name = items[0],
                            NPXX_Code = 2,
                            NPXX_Order = order,
                        });
                    else
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Name = items[2].Trim(),
                            NPXX_Score = int.Parse(items[3]),
                            NPXX_Recommend = items[5],
                            NPXX_Code = 2,
                            NPXX_Order = order,
                        });
                    order += 5;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 解析目前所在地区
        /// </summary>
        /// <param name="lines">要解析的内容</param>
        private void AnalyzeSZDQ(string[] lines)
        {
            nCDP_XXGZFies.Clear();
            nCDP_XXGZFies.Add(new NCDP_XXGZFY
            {
                NPXX_Name = "目前所在地区",
                NPXX_Type = 1,
                NPXX_Order = 20,
                NPXX_Code = 3,
                NPXX_IsRequired = true
            });
            var order = 5;
            try
            {
                foreach (var line in lines)
                {
                    if (line.IsNullOrEmpty())
                        continue;
                    nCDP_XXGZFies.Add(new NCDP_XXGZFY
                    {
                        NPXX_Name = line.Trim(),
                        NPXX_Code = 3,
                        NPXX_Order = order,
                    });
                    order += 5;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 可能感染
        /// </summary>
        /// <param name="lines">要解析的内容</param>
        private void AnalyzeKNGR(string[] lines)
        {
            nCDP_XXGZFies.Clear();
            nCDP_XXGZFies.Add(new NCDP_XXGZFY
            {
                NPXX_Name = "疫情期间可能感染",
                NPXX_Type = 2,
                NPXX_Order = 25,
                NPXX_Code = 4,
                NPXX_IsRequired = false
            });
            var order = 5;
            try
            {
                foreach (var line in lines)
                {
                    if (line.IsNullOrEmpty())
                        continue;
                    var items = line.Split('\t');
                    if (items[2].IsNullOrEmpty())
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Type = 4,
                            NPXX_Name = items[0],
                            NPXX_Code = 4,
                            NPXX_Order = order,
                        });
                    else
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Name = HandleRecommanded(items[2]),
                            NPXX_Score = int.Parse(items[3]),
                            NPXX_Recommend = items[5],
                            NPXX_Code = 4,
                            NPXX_Order = order,
                        });
                    order += 5;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 疑似症状
        /// </summary>
        /// <param name="lines">要解析的内容</param>
        private void AnalyzeYSZZ(string[] lines)
        {
            nCDP_XXGZFies.Clear();
            nCDP_XXGZFies.Add(new NCDP_XXGZFY
            {
                NPXX_Name = "疫情期间疑似症状",
                NPXX_Type = 2,
                NPXX_Order = 30,
                NPXX_Code = 5,
                NPXX_IsRequired = false
            });
            var order = 5;
            try
            {
                foreach (var line in lines)
                {
                    if (line.IsNullOrEmpty())
                        continue;
                    var items = line.Split('\t');
                    if (items[2].IsNullOrEmpty())
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Type = 4,
                            NPXX_Name = items[0],
                            NPXX_Code = 5,
                            NPXX_Order = order,
                        });
                    else
                        nCDP_XXGZFies.Add(new NCDP_XXGZFY
                        {
                            NPXX_Name = HandleRecommanded(items[2]),
                            NPXX_Score = int.Parse(items[3]),
                            NPXX_Recommend = items[5],
                            NPXX_Code = 5,
                            NPXX_Order = order,
                        });
                    order += 5;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 推荐项目
        /// </summary>
        /// <param name="lines">要解析的内容</param>
        private void AnalyzeTJXM(string[] lines)
        {
            try
            {
                var hs = new HashSet<string>();
                foreach (var line in lines)
                {
                    if (line.IsNullOrEmpty())
                        continue;
                    var items = line.Split("\t；".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    foreach (var item in items)
                        hs.Add(HandleRecommanded(item));
                }
                for (int i = hs.Count - 1; i >= 0; i--)
                {
                    if (nCDP_XXGZFYTJXMs.Any(c => c.NPTJ_Content == hs.ElementAt(i)))
                        hs.Remove(hs.ElementAt(i));
                }
                nCDP_XXGZFYTJXMs.Clear();
                nCDP_XXGZFYTJXMs = hs.Select(c => new NCDP_XXGZFYTJXM { NPTJ_Content = c }).ToList();
                this.dgvData.DataSource = null;
                this.dgvData.DataSource = nCDP_XXGZFYTJXMs;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 点击保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //var parent = nCDP_XXGZFies.Find(c => c.NPXX_Type == 1 || c.NPXX_Type == 2 || c.NPXX_Type == 3);
                //var pId = DBContext.SimpleClient.InsertReturnIdentity(parent);
                //var children = nCDP_XXGZFies.Where(c => c != parent).ToList();
                //children.ForEach(c => c.NPXX_ParentID = pId);
                //if (DBContext.SimpleClient.InsertRange(children))
                //    MessageBox.Show("保存成功");
                //else
                //    MessageBox.Show("保存失败");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 保存推荐项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveTJXM_Click(object sender, EventArgs e)
        {
            try
            {
                //if (DBContext.SimpleClient.InsertRange(nCDP_XXGZFYTJXMs))
                //    MessageBox.Show("保存成功");
                //else
                //    MessageBox.Show("保存失败");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 初始化表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInitTable_Click(object sender, EventArgs e)
        {
            //DBContext.SimpleClient.AsSugarClient().CodeFirst.InitTables<NCDP_XXGZFY>();
            //DBContext.SimpleClient.AsSugarClient().CodeFirst.InitTables<NCDP_XXGZFYTJXM>();
            //DBContext.SimpleClient.AsSugarClient().CodeFirst.InitTables<NCDP_XXGZFYScores>();
            //DBContext.SimpleClient.AsSugarClient().CodeFirst.InitTables<NCDP_XXGZFYHandExam>();
            //DBContext.SimpleClient.AsSugarClient().CodeFirst.InitTables<NCDP_XXGZFYSelections>();
            MessageBox.Show("初始化完成");
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetAllData_Click(object sender, EventArgs e)
        {
            try
            {
                this.dgvData.DataSource = null;
                //this.dgvData.DataSource = DBContext.SimpleClient.GetList<NCDP_XXGZFY>();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 获取所有推荐项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetAllTJXM_Click(object sender, EventArgs e)
        {
            try
            {
                this.dgvData.DataSource = null;
                //this.dgvData.DataSource = nCDP_XXGZFYTJXMs = DBContext.SimpleClient.GetList<NCDP_XXGZFYTJXM>();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 点击删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            if (this.dgvData.SelectedRows?.Count == 0)
                return;
            if (MessageBox.Show("确定要删除吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                return;
            var ids = this.dgvData.SelectedRows.OfType<DataGridViewRow>().Select(c => (dynamic)c.Cells["NPXX_ID"].Value).ToArray();
            //if (DBContext.SimpleClient.DeleteByIds<NCDP_XXGZFY>(ids))
            //{
            //    this.dgvData.DataSource = null;
            //    this.dgvData.DataSource = DBContext.SimpleClient.GetList<NCDP_XXGZFY>();
            //}
        }

        #endregion
    }

    public class StringEqualCompare : IEqualityComparer<NCDP_XXGZFYTJXM>
    {
        public bool Equals(NCDP_XXGZFYTJXM x, NCDP_XXGZFYTJXM y)
        {
            return x.NPTJ_Content == y.NPTJ_Content;
        }

        public int GetHashCode(NCDP_XXGZFYTJXM obj)
        {
            return obj.GetHashCode();
        }
    }
}
